<?php
namespace App\Exports;
use App\Models\Order;
use App\Models\UsersWechat;

use Maatwebsite\Excel\Concerns\FromCollection;
use Maatwebsite\Excel\Concerns\WithHeadings;    //设置标题
use Maatwebsite\Excel\Concerns\ShouldAutoSize;      //自动单元格尺寸
use PhpOffice\PhpSpreadsheet\Style\NumberFormat;      //设置单元格数据格式
use Maatwebsite\Excel\Concerns\WithColumnFormatting;       //设置列格式
 

/**
 * 导出订单
 */
class OrderExport implements FromCollection,WithHeadings
{

	public function __construct($data= [])
    {
        $this->data = $data;
    }

    public function collection()
    {
    	$data = $this->data;
    	$query = Order::with('user')->where('pay_status',2);
    	if ($data['username']) {
            $user = UsersWechat::select('id')->where('nickname','like',"%{$data['username']}%")->get()->toArray();
            $ids = [];
            foreach ($user as $key => $id) {
                $ids[] = $id;
            }
            $query->whereIn('wechat_id',$ids);
        }
        if ($data['order_no']) {
            $query->where('order_no',$data['order_no']);
        }
        if ($data['created_at']) {
            $query->whereDate('created_at',$data['created_at']);
        }
        $rows =  $query->get();
        $cellData = [];
        foreach ($rows as $key => $row) {
            $akey = [
                $key+1,
                $row->order_no,
                $row->name,
                $row->created_at,
                $row->user->nickname,
                $row->getTotalAmountHandleAttribute(),
                $row->getPayStatusHandleAttribute(),
                $row->getPayTypeHandleAttribute(),
                $row->pay_time,
            ];
            array_push($cellData,$akey);
            unset($akey);
        }
        return collect($cellData);
    }

    //首行标题
    public function headings(): array
    {
        return [
            '序号',
            '订单号',
            '订单名称',
            '创建时间',
            '用户',
            '支付金额',
            '订单状态',
            '订单类型',
            '支付时间'
        ];
    }

}